package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.TbUser;
import com.bwie.es.EsUser;
import com.bwie.mapper.TbUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/10/24 13:10
 */

@Component
@Slf4j
public class SyncUserTask implements Job {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    TbUserMapper tbUserMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("同步用户数据到ES的任务开始了");
        //--1 检查并创建索引
        // 我们在存储数据到ES的时候，不要用数据库的对象，需要自己定义
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsUser.class);
        if(!indexOps.exists()) {
            // 索引不存在就创建
            indexOps.create();

            // 创建映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }

        //--2 查询数据库
        List<TbUser> tbUsers = tbUserMapper.selectList(null);

        //--3 把数据库的对象转换为ES对象，然后存到ES中
        for (TbUser tbUser : tbUsers) {
            EsUser esUser = BeanUtil.toBean(tbUser, EsUser.class);
            elasticsearchRestTemplate.save(esUser);
        }

        log.info("同步用户数据到ES的任务完成了");
    }
}
